#include "sys_tick.h"
static u8  fac_us=0;							//us延时倍乘数			   
static u16 fac_ms=0;							//ms延时倍乘数,在os下,代表每个节拍的ms数

//THUMB指令不支持汇编内联
//采用如下方法实现执行汇编指令WFI  
__asm void WFI_SET(void)
{
	WFI;		  
}
//关闭所有中断(但是不包括fault和NMI中断)
__asm void INTX_DISABLE(void)
{
	CPSID   I
	BX      LR	  
}
//开启所有中断
__asm void INTX_ENABLE(void)
{
	CPSIE   I
	BX      LR  
}
//设置栈顶地址
//addr:栈顶地址
__asm void MSR_MSP(u32 addr) 
{
	MSR MSP, r0 			//set Main Stack value
	BX r14
}

void systick_delay_us(u32 nus)
{		
    u32 temp;
    SysTick->LOAD=nus*fac_us;
    SysTick->VAL=0x00;
    SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk;
    do
    {
        temp=SysTick->CTRL;
    }while((temp&0x01)&&!(temp&(1<<16)));
    SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk;
    SysTick->VAL =0X00;
}

void delay_xms(u16 nms)
{
    u32 temp;
    SysTick->LOAD=(u32)nms*fac_ms;
    SysTick->VAL =0x00;
    SysTick->CTRL|=SysTick_CTRL_ENABLE_Msk;
    do
    {
        temp=SysTick->CTRL;
    }while((temp&0x01)&&!(temp&(1<<16)));
    SysTick->CTRL&=~SysTick_CTRL_ENABLE_Msk;
    SysTick->VAL =0X00;
}

void systick_delay_ms(u16 nms)
{
    u8 repeat=nms/540;
    u16 remain=nms%540;
    while(repeat)
    {
        delay_xms(540);
        repeat--;
    }
    if(remain)delay_xms(remain);
} 

uint32_t sys_get_clk_info(void)
{
    RCC_ClocksTypeDef get_rcc_clock;
    RCC_GetClocksFreq(&get_rcc_clock);
    switch (RCC_GetSYSCLKSource())
    {
        case 0x00:
            DBG_MSG("HSI used as system clock\r\n");
        break;

        case 0x04:
            DBG_MSG("HSE used as system clock\r\n");
        break;

        case 0x08:
            DBG_MSG("PLL used as system clock\r\n");
        break;

        default:
            break;
    }
    DBG_MSG("SYSCLK_Frequency:%dMHz\r\n",get_rcc_clock.SYSCLK_Frequency/1000000);
    DBG_MSG("AHBCLK_Frequency  :%dMHz\r\n",get_rcc_clock.HCLK_Frequency/1000000);
    DBG_MSG("APB1CLK_Frequency :%dMHz\r\n",get_rcc_clock.PCLK1_Frequency/1000000);
    DBG_MSG("APB2CLK_Frequency :%dMHz\r\n",get_rcc_clock.PCLK2_Frequency/1000000);
    DBG_MSG("fw time:%s %s\r\n",__DATE__,__TIME__);
    return get_rcc_clock.SYSCLK_Frequency/1000000;
}

void systick_delay_init(u8 SYSCLK)
{
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
    fac_us=SYSCLK/8;
    fac_ms=(u16)fac_us*1000;
}

void sys_reset(void)
{
    SCB->AIRCR =0X05FA0000|(u32)0x04;
}
